""" 测试Ajax"""
import json
from django import forms
from django.shortcuts import render,HttpResponse
# 导入csrf_exempt Ajax通过POST方式访问的时候不会报错,免认证
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
# 导入分页
from app01.utils.pagination import Pagination


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.Textarea,
            # "detail": forms.TextInput,
        }

def task_list(request):
    """任务列表"""
    # Ajax实现提交按钮，刷新任务列表
    # 在数据库获取所有任务,按ID倒序排序
    queryset = models.Task.objects.all().order_by('-id')
    # 导入分页
    page_object = Pagination(request, queryset,page_size=5)

    form = TaskModelForm()
    context = {
        'form': form,
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }

    return render(request,'task_list.html',context)

@csrf_exempt
def task_ajax(request):
    print(request.POST)
    print(request.GET)

    data_dict = {"status": True,"data": [11,22,33,44,55]}
    return HttpResponse(json.dumps(data_dict))

# 这个糖语法的作用是，Ajax提交免写csrf token 认证
@csrf_exempt
def task_add(request):
    # print(request.POST)
    # <QueryDict: {'level': ['3'], 'title': ['测试'], 'detail': ['test'], 'user': ['1']}>

    # 1,用户发送过来的数据进行校验（ModelForm进行校验）
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
         form.save()

         data_dict = {"status": True}
         return HttpResponse(json.dumps(data_dict))

    # print(form.errors,type(form.errors))
    data_dict = {"status": False,'error':form.errors}
    return HttpResponse(json.dumps(data_dict,ensure_ascii=False))